﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using TimeTracker.Client.Data;

namespace TimeTracker.Client
{
	/// <summary>
	/// Interaction logic for TimeSheetWindow.xaml
	/// </summary>
	public partial class TimeSheetWindow
	{
		private readonly LocalDataContext _dc;
		private DateTime _date;

		public TimeSheetWindow()
		{
			InitializeComponent();

			var odpData = (ObjectDataProvider)Resources[ "odpData" ];
			_dc = (LocalDataContext) odpData.ObjectInstance;
		}

		#region Event Handlers

		private void Show_Click( object sender, RoutedEventArgs e )
		{
			RefreshTimeEntriesSource();
		}

		private void Add_Click( object sender, RoutedEventArgs e )
		{
			if( !SelectionIsValid() )
			{
				return;
			}
			// create new entry, defaulting to 8am - 6pm with 30 min break
			var entry = new TimeEntry
			            	{
			            		Employee = ( (Employee) cboEmployee.SelectedItem ),
			            		Start = new DateTime( _date.Year, _date.Month, _date.Day, 8, 0, 0 ),
			            		Stop = new DateTime( _date.Year, _date.Month, _date.Day, 16, 0, 0 ),
			            		BreakTimeMinutes = 30
			            	};

			((List<TimeEntry>)lstTimeEntries.ItemsSource).Add( entry );
			lstTimeEntries.Items.Refresh();

			_dc.TimeEntries.InsertOnSubmit( entry );
		}

		private void Save_Click( object sender, RoutedEventArgs e )
		{
			_dc.SubmitChanges();
			RefreshTimeEntriesSource();
		}

		#endregion

		private void RefreshTimeEntriesSource()
		{
			if( !SelectionIsValid() )
			{
				return;
			}
			var employee = cboEmployee.SelectedItem;

			// NOTE: these two are equivalent
			//var source = _dc.TimeEntries.Where( te => te.Employee == employee && te.Start.Year == _date.Year && te.Start.Month == _date.Month && te.Start.Day == _date.Day ).OrderBy( te => te.Start );
			var source = from te in _dc.TimeEntries
			             where te.Employee == employee
			                   && te.Start.Year == _date.Year
							   && te.Start.Month == _date.Month
							   && te.Start.Day == _date.Day
			             orderby te.Start
			             select te;
			lstTimeEntries.ItemsSource = source.ToList();
		}

		private bool SelectionIsValid()
		{
			if( cboEmployee.SelectedItem == null )
			{
				MessageBox.Show( "Must select an employee first", "Time Tracker - Error", MessageBoxButton.OK, MessageBoxImage.Error );
				return false;
			}
			if( !DateTime.TryParse( txtTimesheetDate.Text, out _date ) )
			{
				MessageBox.Show( "Must enter a valid date", "Time Tracker - Error", MessageBoxButton.OK, MessageBoxImage.Error );
				return false;
			}

			return true;
		}
	}
}
